package com.mooc.lib_user.ui.user

import android.view.View
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.mooc.lib_common.CommonApp
import com.mooc.lib_common.bus.LiveDataBus
import com.mooc.lib_common.model.UserEntity
import com.mooc.lib_network.entity.NetResult
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

class UserViewModel : ViewModel(){
    val repo = UserRepo()
    val userBus = LiveDataBus<UserEntity>()

    fun requestUser(userId : Int){
        viewModelScope.launch(Dispatchers.IO){
            val result = repo.requestUser(userId)
            if (result is NetResult.Success){
                result.data!!.data!!.description = "默认值"
                //更新本地数据库数据
                CommonApp.db.userDao().updateUser(result.data!!.data!!)
                CommonApp.userEntity = result.data!!.data!!
                userBus.postValue(result.data!!.data)
            }
        }
    }

    fun logoutClick() {
        //清理本地room数据
        viewModelScope.launch(Dispatchers.IO){
            CommonApp.db.userDao().delAllUser()
            CommonApp.userEntity = null
        }
    }

}